﻿using AiMoBridge.Paths;
using System.IO;
using System.Text;

namespace AiMoWindows
{
    class ExternalSettings
    {
        private static string scriptsFolderWithHistory = "";
        private static string password = "";
        private static string userName = "";
        private static double editorFontSize = 12;
        private static bool modified = true; // 第一次要允许载入 Load
        public static string UserName
        {
            get => userName;
            set
            {
                userName = value;
                modified = true;
            }
        }
        public static string Password
        {
            get => password;
            set
            {
                password = value;
                modified = true;
            }
        }
        public static double EditorFontSize
        {
            get => editorFontSize; set
            {
                editorFontSize = value;
                modified = true;
            }
        }
        public static string ScriptsFolderWithHistory
        {
            get => scriptsFolderWithHistory; set
            {
                scriptsFolderWithHistory = value;
                modified = true;
            }
        }

        static readonly char[] separator = new char[] { ']', '[' };

        public static void Load()
        {
            // 没有修改过数据，则不需要再一次载入？？？？
            if (!modified) return;
            userName = "";
            password = "";
            scriptsFolderWithHistory = PathManager.ScriptsFolder;
            try
            {
                if (File.Exists(PathManager.InfoTxt))
                {
                    var lines = File.ReadAllLines(PathManager.InfoTxt, Encoding.UTF8);
                    foreach (var line in lines)
                    {
                        string[] pair = line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                        if (pair.Length > 1)
                        {
                            if (pair[0] == "AimoLoginUserName")
                            {
                                string userNameTextEncode = pair[1];
                                if (!string.IsNullOrWhiteSpace(userNameTextEncode))
                                    userName = Decode(userNameTextEncode);
                            }
                            else if (pair[0] == "AimoLoginPassword")
                            {
                                string passwordTextEncode = pair[1];
                                if (!string.IsNullOrWhiteSpace(passwordTextEncode))
                                    password = Decode(passwordTextEncode);
                            }
                            else if (pair[0] == "ScriptsFolderWithHistory")
                            {
                                string path = pair[1];
                                if (Directory.Exists(path))
                                    scriptsFolderWithHistory = path;
                            }
                            else if (pair[0] == "EditorFontSize")
                            {
                                if (double.TryParse(pair[1], out double value))
                                {
                                    editorFontSize = value;
                                }
                            }
                        }
                    }
                }
                modified = false;
                // 载入之后，所有数据都是最新的。
                modified = false;
            }
            catch { }
        }
        public static void Save()
        {
            // if not modified, no need to save
            if (!modified) return;
            try
            {
                string[] lines;
                if (File.Exists(PathManager.InfoTxt))
                    lines = File.ReadAllLines(PathManager.InfoTxt, Encoding.UTF8);
                else
                {
                    lines = Array.Empty<string>();
                }
                Dictionary<string, string> maps = new Dictionary<string, string>();
                foreach (string line in lines)
                {
                    string[] pair = line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                    if (pair.Length > 1)
                    {
                        maps[pair[0]] = pair[1];
                    }
                }
                maps["AimoLoginUserName"] = Encode(userName);
                maps["AimoLoginPassword"] = Encode(password);
                maps["ScriptsFolderWithHistory"] = scriptsFolderWithHistory;
                maps["EditorFontSize"] = editorFontSize.ToString();
                File.WriteAllLines(PathManager.InfoTxt, maps.Select(x => $"[{x.Key}]{x.Value}").ToArray(), Encoding.UTF8);
                modified = false;
            }
            catch { }
        }

        static string Encode(string input)
        {
            if (string.IsNullOrWhiteSpace(input)) return "";
            return Convert.ToBase64String(Inverse(Encoding.UTF8.GetBytes(input)));
        }

        static byte[] Inverse(byte[] bytes)
        {
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = (byte)(byte.MaxValue - bytes[i]);
            }
            return bytes;
        }
        static string Decode(string input)
        {
            if (string.IsNullOrWhiteSpace(input)) return "";
            return UTF8Encoding.UTF8.GetString(Inverse(Convert.FromBase64String(input)));
        }
    }
}
